﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Windows.Forms;
using System.Collections;
using System.Security.Cryptography;

namespace HomeTask03
{
    class EncodeThread 
    {
        private string OK_STRING = "Completed";
        private JobPanel oneJobPanel;
        string thrdName;
        Form1 ThrdForm;
        Rijndael alg;
        Boolean isDecrypt;
        public EncodeThread(Form1 AppForm, string name, JobPanel jp, Rijndael algPass) 
        {
            thrdName = name;
            oneJobPanel = jp;
            ThrdForm = AppForm;
            alg = algPass;
            isDecrypt = jp.isDecrypt;
        }
        
        
        public void Run()
        {
            int sin;
            long n,i;
            double proc;
            FileStream fin;
            FileStream fout;
            CryptoStream cs;
            try
            {
                fin = new FileStream((String)oneJobPanel.getSourse(), FileMode.Open,FileAccess.Read);
            }
            catch (FileNotFoundException exc)
            {
                ThrdForm.Invoke(ThrdForm.jpStatus, thrdName, exc.Message, true);
                return;
            }

            try
            {
                fout = new FileStream((String)oneJobPanel.getDestination(), FileMode.Create, FileAccess.Write);
            }
            catch (IOException exc)
            {
                ThrdForm.Invoke(ThrdForm.jpStatus, thrdName, exc.Message,true);
                return;
            }

            if (isDecrypt) { cs = new CryptoStream(fout, alg.CreateDecryptor(), CryptoStreamMode.Write); }
               else cs = new CryptoStream(fout,alg.CreateEncryptor(), CryptoStreamMode.Write);
            
                n = fin.Length;
                proc = n / 100;
                i = 0;

                do
                {
                    sin = fin.ReadByte();
                    i++;
                    if (i >= proc)
                    {
                        ThrdForm.Invoke(ThrdForm.PbInc, thrdName); i = 0; 
                    }
                    if (sin != -1)
                    {
                        cs.WriteByte((byte)sin);
                    }
                } while (sin != -1);

                fin.Close();    
                try
                {
                     cs.Close();// this will also close the unrelying fout stream
                }
                catch (CryptographicException exc) {
                    ThrdForm.Invoke(ThrdForm.jpStatus, thrdName, exc.Message, true);
                    return;
                }

             
            //Set statusstring color, text and set isComplete property if succeed
             ThrdForm.Invoke(ThrdForm.jpStatus, thrdName, OK_STRING, false);
        }
    }

}
